//
//  WmcSearchView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/6/9.
//

import UIKit
import YPBedrock

// MARK: - [WmcSearchView]

class WmcSearchView: WmcBaseView {
    // Lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    @available(*, unavailable)
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    convenience init(placeholderText: String = "输入内容进行搜索",
                     placeholderColor: UIColor = .wmc_grayH11_9D9DB3,
                     font: UIFont)
    {
        self.init(frame: .zero)
        setPlaceholder(placeholderText: placeholderText,
                       placeholderColor: placeholderColor,
                       font: font)
    }

    // Internal

    lazy var searchIconView: UIImageView = {
        let view = UIImageView(image: "search".wmc_image.yp.set(tintColor: UIColor.wmc_grayH11_9D9DB3))
        return view
    }()

    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.textColor = .wmc_grayH2_323233
        textField.font = 14.wmc_font
        textField.backgroundColor = .wmc_grayH19_F5F5F5
        textField.returnKeyType = .search
        textField.clearButtonMode = .whileEditing
        textField.delegate = self
        return textField
    }()

    /// 文字变化回调
    var textDidChangeBlock: YPBlock.OneParam<String>?
    
    override func makeUI() {
        backgroundColor = .wmc_grayH19_F5F5F5
        layer.cornerRadius = 4
        layer.masksToBounds = true

        addSubview(searchIconView)
        searchIconView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.bottom.equalTo(-8)
            make.left.equalTo(12)
            make.width.equalTo(searchIconView.snp.height)
        }

        addSubview(textField)
        textField.snp.makeConstraints { make in
            make.top.bottom.right.equalToSuperview()
            make.left.equalTo(searchIconView.snp.right).offset(4)
        }
    }

    /// 设置占位文字
    func setPlaceholder(placeholderText: String,
                        placeholderColor: UIColor,
                        font: UIFont)
    {
        textField.attributedPlaceholder =
            placeholderText.yp.makeAttributed { make in
                make.set(foregroundColor:placeholderColor)
            }
        textField.font = font
    }
}

// MARK: - UITextFieldDelegate

extension WmcSearchView: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        guard let text = textField.text else { return }
        textDidChangeBlock?(text)
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "\n" {
            textField.resignFirstResponder()
            return false
        }
        return true
    }
}
